<?php
include 'head.php';

$filter = '';
if($_GET['cat']) {
    $cat = (int)$_GET['cat'];

    if($cat > 0) {
        $filter .= 'WHERE p.category = '.$cat;
    }
}

if($_GET['tag']) {
    $tag = $_GET['tag'];

    if($cat > 0) {
        $filter .= ' AND ';
    } else {
        $filter = 'WHERE ';
    }

    $filter .= 'p.tags LIKE "%'.$tag.'%"';
}

if($_GET['page']) {
    $p = (int)$_GET['page'];
} else {
    $p = 1;
}
$results = 5;
$startFrom = ($p - 1) * $results;

$page_uri = '&page='.$p;
$data['uri'] = str_replace($page_uri, '', $_SERVER['QUERY_STRING']);

$posts = fetchAll(query('SELECT p.*, (SELECT COUNT(*) FROM comments as c WHERE p.id = c.post_id AND c.reply_to = 0) as comments 
        FROM posts as p '.$filter.' ORDER BY `time` DESC LIMIT '.$startFrom.', '.$results.''));

if($posts && $posts[0]['id'] != null) {
    
    foreach($posts as $key => $val) {
        $posts[$key]['tags'] = explode(',', $posts[$key]['tags']);
    }
    
    $data['posts'] = $posts;
}

$postsNum = fetch(query('SELECT COUNT(*) as num FROM posts as p '.$filter))['num'];
$data['pagination']['pages'] = ceil($postsNum / $results);
$data['pagination']['current_page'] = $p;

$widgets = true;
$cats = fetchAll(query('SELECT c.*, (SELECT COUNT(*) FROM posts as p WHERE p.category = c.id) as posts FROM categories as c'));
foreach($cats as $c) {
    $categories[$c['id']] = $c;
}

$data['categories'] = $categories;
$data['tags'] = getTags();

include 'load_smarty.php';
